<!-- 城市区域 复选框 -->
<template>
  <ele-modal
    width="700px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    title="选择城市"
    @update:visible="updateVisible"
  >
    <el-checkbox :indeterminate="indeterminate" v-model="ischeckAll" @change="handleCheckAllChange" style="margin-bottom: 15px">全选</el-checkbox>
    <div class="flex-wrap">
      <div v-for="(city,cityIndex) in list" :label="city" :key="cityIndex" style="margin-right: 20px">
        <el-popover
          trigger="hover"
          placement="bottom"
          width="370"
        >
          <!--选择城市 第二级（省）-->
          <el-checkbox style="min-width: 100px;margin-bottom: 15px" :label="city" slot="reference" v-model="city.selected" :indeterminate="city.indeterminate" @change="handleCheckedCountryAllChange(cityIndex,city.areaId,$event)" :key="cityIndex">
            {{city.areaName}}
          </el-checkbox>
          <!--选择子级 第三级（市）-->
          <el-checkbox v-for="i in city.country" v-model="i.selected" @change="handleCheckedCountryChange(cityIndex,i.areaId,city.areaId,$event)" :label="i" :key="i.areaId">
            {{i.areaName}}
          </el-checkbox>
        </el-popover>
      </div>
    </div>
    <div class="btn-class flex">
      <el-button size="small" @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" size="small" @click="confirm()">确定</el-button>
    </div>
  </ele-modal>
</template>

<script>
  export default {
    name: "areaList",
    props: {
      // 弹窗是否打开
      visible: Boolean,
      list: Array,
      oldList: Array
    },
    data() {
      return {
        indeterminate:false,
        ischeckAll:false,//一级全选状态
        checkedCities: [],
        cities: this.list
      };
    },
    methods: {
      // 子组件一进入的事件
      show(){
        // if this.oldList（编辑返回省市二级数据），存在，则重新对比赋值
        if(this.oldList.length<=0){
          return
        }
        this.list.filter(item => this.oldList.some(ele=> {
          if(ele.areaCode == item.areaCode ){
            console.log('ele.areaCode',ele.areaCode,ele.areaName)
            item.selected=ele.selected
            if(ele.indeterminate){
              item.indeterminate=ele.indeterminate
            }
            let country = item.country
            let oldCountry = ele.country
            oldCountry.filter(nows => country.some(befores=> {
              if(befores.areaCode == nows.areaCode ){
                console.log('nows.areaCode',nows.areaCode,nows.areaName)
                befores.selected=nows.selected
                // item.country
              }
            }))


          }
        }))
        /*let index = arr.findIndex(item => item.id === 2);  // 查找id为2的元素索引
        if (index !== -1) {  // 如果找到了
          arr.splice(index, 1, {id: 2, name: 'd'});  // 使用splice方法替换元素
        }*/
        console.log("this.oldList",this.oldList,'this.list',this.list)
        return
      },
      //一级change事件
      handleCheckAllChange(e){
        this.ischeckAll = e
        if(e == true){
          this.indeterminate = false
          for(var i=0,len=this.list.length; i<len; i++){ //二级全选反选不确定
            this.list[i].selected = e
            for(var j=0,len1=this.list[i].country.length; j<len1; j++){
              this.list[i].country[j].selected = e
            }
          }
        }else{
          this.indeterminate = false
          for(var i=0,len=this.list.length; i<len; i++){ //三级全选反选不确定
            this.list[i].selected = e
            for(var j=0,len1=this.list[i].country.length; j<len1; j++){
              this.list[i].country[j].selected = e
            }
          }
        }
        console.log('this.ischeckAll',this.ischeckAll)
      },
      //二级change事件
      handleCheckedCountryAllChange(index, topId, e){
        console.log("index, topId, e",index, topId, e)
        this.list[index].selected = e//二级勾选后，子级全部勾选或者取消
        console.log('this.list[index]',this.list[index])
        if(e == false) this.list[index].indeterminate = false //去掉二级不确定状态
        var childrenArray = this.list[index].country
        if(childrenArray)
          for(var i=0,len=childrenArray.length; i<len; i++)
            childrenArray[i].selected = e
        console.log("二级change事件this.list",this.list)
        this.getIsCheckAll()
      },
      //三级change事件
      handleCheckedCountryChange(topIndex, sonId, topId, e){
        var childrenArray = this.list[topIndex].country
        var tickCount = 0, unTickCount = 0, len = childrenArray.length
        for(var i = 0; i < len; i++){
          if(sonId == childrenArray[i].id) childrenArray[i].selected = e
          if(childrenArray[i].selected == true) tickCount++
          if(childrenArray[i].selected == false) unTickCount++
        }
        if(tickCount == len) {//三级级全勾选
          this.list[topIndex].selected = true
          this.list[topIndex].indeterminate = false
        } else if(unTickCount == len) {//三级级全不勾选
          this.list[topIndex].selected = false
          this.list[topIndex].indeterminate = false
        } else {
          this.list[topIndex].selected = false
          this.list[topIndex].indeterminate = true //添加二级不确定状态
        }

        this.getIsCheckAll()
      },
      getIsCheckAll(){
        var tickCount = 0, unTickCount = 0, ArrLength = this.list.length
        for(var j=0; j<ArrLength; j++){//全选checkbox状态
          if(this.list[j].selected == true) tickCount++
          if(this.list[j].selected == false) unTickCount++
        }
        console.log('this.list',this.list,'tickCount',tickCount,'ArrLength',ArrLength)
        if(tickCount == ArrLength) {//二级全勾选
          this.ischeckAll = true
          this.indeterminate = false
        } else if(unTickCount == ArrLength) {//二级全不勾选
          this.ischeckAll = false
          this.indeterminate = false
        } else {
          this.ischeckAll = false
          this.indeterminate = true //添加一级不确定状态
        }
      },
      // 确定选择城市
      confirm(){
        // 赋值不改变原数组
        let list = JSON.parse(JSON.stringify(this.list));
        let screenList=[]
        let objList=[]  // 新增修改
        let ids=""
        // 保留两个需要的字段
        list = list.map(({areaCode,areaName,selected,indeterminate,country,areaId})=>{
          // return {areaCode,areaName,selected,indeterminate,country,areaId};
          return {areaCode,selected,indeterminate,country,areaId};
        })
        screenList=list.filter(item => {
          console.log("item11111",item)
          // 新增修改 start
          if(item.selected == true ||  item.indeterminate == true){
            let info= JSON.parse(JSON.stringify(item));
            delete info.country
            objList.push(info)
          }
          // end
          return item.selected == true ||  item.indeterminate == true;
        });
        for(let i=0;i<screenList.length;i++){
          let countList= []
          countList=screenList[i].country.filter(item => {
            // 新增修改 start
            if(item.selected == true){
              let infos= JSON.parse(JSON.stringify(item));
              const obj = {
                areaCode: infos.areaCode,
                parentId: infos.parentId,
                selected: infos.selected,
              };
              objList.push(obj)
            }
            // end
            return item.selected == true;
          });
          countList = countList.map(({areaCode,areaName,selected,parentId})=>{
            return {areaCode,selected,parentId};
            // return {areaCode,areaName,selected,parentId};
          })
          screenList[i].country=countList
        }
        console.log('screenList测试',screenList,'objList',objList)
        // 获取选中的市id
        for(let i=0;i<this.list.length;i++){
          for(let j=0;j<this.list[i].country.length;j++){
            if(this.list[i].country[j].selected==true){  // 市
              ids+=this.list[i].country[j].areaName+','
            }
          }
        }
        console.log('ids======',ids,'screenList',screenList)
        // this.$emit('cityClick', ids,screenList)
        this.$emit('cityClick', ids,objList)
        this.updateVisible(false)
      },
      // 弹出框 visible
      updateVisible(value) {
        this.$emit('update:visible', value);
      },
    }
  };
</script>

<style scoped>
  .btn-class{
    margin:50px 0 20px
  }
</style>
